package priv.xakml.demo.valid;

import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author lhx
 * @date 2021-05-25 11:30
 **/
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 参数验证异常(前端json格式提交)
     *
     * @param e 异常
     * @return 响应实体
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public String handleParameterException(MethodArgumentNotValidException e) {
        log.error(e.getMessage(), e);
        String errorMessage = CommonUtil.getErrorMessage(e.getBindingResult());
        return errorMessage;
    }

    /**
     * 参数验证异常(前端form表单格式提交)
     *
     * @param exception 异常
     * @return http响应对象
     */
    @ExceptionHandler(BindException.class)
    public String handlerBindException(BindException exception) {
        String errorMessage = CommonUtil.getErrorMessage(exception.getBindingResult());
        return errorMessage;
    }
}
